package com.jimmy.dreamer;

import android.app.Activity;
import android.os.Bundle;
import static android.provider.BaseColumns._ID;
import static com.jimmy.dreamer.DbConstants1.DREAM;
import static com.jimmy.dreamer.DbConstants1.TABLE_NAME;
import static com.jimmy.dreamer.Dreamer.isLogin;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.app.AlertDialog;

public class Record extends Activity implements OnClickListener{
	private DbHelper1 dbhelper = null;

    private EditText content = null;
    private Button btnPost = null;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.record);
        
        initView();

        openDatabase();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        closeDatabase();
    }
    private void openDatabase(){
        dbhelper = new DbHelper1(this); 
    }

    private void closeDatabase(){
        dbhelper.close();
    }

    private void initView(){
    	content = (EditText) findViewById(R.id.txt_dream);
        btnPost = (Button) findViewById(R.id.btn_post);
        btnPost.setOnClickListener(this);
    }
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.btn_post:
        	if(isLogin){
        		add();
        		Intent d = new Intent(this, Dreamer.class);
        		startActivity(d);
        	}
        	else{
        		AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        		alertDialog.setTitle("Login?");
        		alertDialog.setMessage("Did you forget to login?");
        		alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
        		   public void onClick(DialogInterface dialog, int which) {
        			   Intent d = new Intent(Record.this, Dreamer.class);
               		   startActivity(d);
        		   }
        		});
        		alertDialog.setIcon(R.drawable.ic_launcher);
        		alertDialog.show();
        	}
            break;

        default:
        }
    }
    private void add(){
        SQLiteDatabase db = dbhelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(DREAM, content.getText().toString());
        db.insert(TABLE_NAME, null, values);
    }
}
